package cn.itcast.protocol.xt;

import cn.itcast.message.xt.IoTMessage;
import cn.itcast.protocol.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
@ChannelHandler.Sharable
public class IoTRespMessageCodec extends MessageToMessageCodec<ByteBuf, IoTMessage> {

    @Override
    protected void encode(ChannelHandlerContext ctx, IoTMessage msg, List<Object> outList) throws Exception {
        ByteBuf out = ctx.alloc().buffer();
        // 1. 4 字节的魔数
        out.writeBytes(new byte[]{0x58, 0x49, 0x54, 0x55});
        // 2. 1 字节的版本,
        out.writeByte(1);
        // 3. 1 字节的序列化方式 json 1
        out.writeByte(1);
        // 4. 1 字节的指令类型
        out.writeByte(msg.getMessageType());
        // 无意义，对齐填充
//        out.writeByte(0x00);
        // 6. 获取内容的字节数组
        byte[] bytes = Serializer.Algorithm.Json.serialize(msg);
        // 7. 长度
        out.writeInt(bytes.length);
        // 8. 写入内容
        out.writeBytes(bytes);
        outList.add(out);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        int magicNum = in.readInt();
        byte version = in.readByte();
        byte serializerType = in.readByte();
        byte messageType = in.readByte();
//        in.readByte();
        int length = in.readInt();
        byte[] bytes = new byte[length];
        in.readBytes(bytes, 0, length);
        IoTMessage message = (IoTMessage) Serializer.Algorithm.Json.deSerialize(IoTMessage.getMessageClass(messageType), bytes);
        log.debug("{}, {}, {}, {}, {}", magicNum, version, serializerType, messageType, length);
        log.debug("{}", message);
        out.add(message);
    }
}
